package com.ruoyi.system.service.estate.emergency.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Calendar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.mapper.estate.emergency.EmergencySuppliesMapper;
import com.ruoyi.system.mapper.estate.emergency.EmergencySuppliesStockMapper;
import com.ruoyi.system.mapper.estate.emergency.EmergencySuppliesRecordMapper;
import com.ruoyi.system.domain.estate.emergency.EmergencySupplies;
import com.ruoyi.system.domain.estate.emergency.EmergencySuppliesStock;
import com.ruoyi.system.domain.estate.emergency.EmergencySuppliesRecord;
import com.ruoyi.system.service.estate.emergency.IEmergencySuppliesStockService;
import com.ruoyi.system.service.estate.emergency.IEmergencySuppliesRecordService;

/**
 * 应急物资库存Service业务层处理
 */
@Service
public class EmergencySuppliesStockServiceImpl implements IEmergencySuppliesStockService {
    @Autowired
    private EmergencySuppliesStockMapper emergencySuppliesStockMapper;
    
    @Autowired
    private EmergencySuppliesMapper emergencySuppliesMapper;
    
    @Autowired
    private EmergencySuppliesRecordMapper emergencySuppliesRecordMapper;

    @Autowired
    private IEmergencySuppliesRecordService emergencySuppliesRecordService;

    /**
     * 查询应急物资库存列表
     * 
     * @param emergencySuppliesStock 应急物资库存信息
     * @return 应急物资库存集合
     */
    @Override
    public List<EmergencySuppliesStock> selectEmergencySuppliesStockList(EmergencySuppliesStock emergencySuppliesStock) {
        return emergencySuppliesStockMapper.selectEmergencySuppliesStockList(emergencySuppliesStock);
    }

    /**
     * 查询应急物资库存详细信息
     * 
     * @param stockId 应急物资库存ID
     * @return 应急物资库存信息
     */
    @Override
    public EmergencySuppliesStock selectEmergencySuppliesStockById(Long stockId) {
        return emergencySuppliesStockMapper.selectEmergencySuppliesStockById(stockId);
    }

    /**
     * 新增应急物资库存
     * 
     * @param emergencySuppliesStock 应急物资库存信息
     * @return 结果
     */
    @Override
    public int insertEmergencySuppliesStock(EmergencySuppliesStock emergencySuppliesStock) {
        emergencySuppliesStock.setCreateTime(DateUtils.getNowDate());
        emergencySuppliesStock.setCreateBy(SecurityUtils.getUsername());
        if (emergencySuppliesStock.getStatus() == null) {
            emergencySuppliesStock.setStatus("0");
        }
        return emergencySuppliesStockMapper.insertEmergencySuppliesStock(emergencySuppliesStock);
    }

    /**
     * 修改应急物资库存
     * 
     * @param emergencySuppliesStock 应急物资库存信息
     * @return 结果
     */
    @Override
    public int updateEmergencySuppliesStock(EmergencySuppliesStock emergencySuppliesStock) {
        emergencySuppliesStock.setUpdateTime(DateUtils.getNowDate());
        emergencySuppliesStock.setUpdateBy(SecurityUtils.getUsername());
        return emergencySuppliesStockMapper.updateEmergencySuppliesStock(emergencySuppliesStock);
    }

    /**
     * 批量删除应急物资库存
     * 
     * @param stockIds 需要删除的应急物资库存ID
     * @return 结果
     */
    @Override
    public int deleteEmergencySuppliesStockByIds(Long[] stockIds) {
        return emergencySuppliesStockMapper.deleteEmergencySuppliesStockByIds(stockIds);
    }

    /**
     * 删除应急物资库存信息
     * 
     * @param stockId 应急物资库存ID
     * @return 结果
     */
    @Override
    public int deleteEmergencySuppliesStockById(Long stockId) {
        return emergencySuppliesStockMapper.deleteEmergencySuppliesStockById(stockId);
    }
    
    /**
     * 物资入库
     * 
     * @param stock 应急物资库存信息
     * @return 结果
     */
    @Override
    @Transactional
    public int stockIn(EmergencySuppliesStock stock) {
        // 1. 获取物资信息
        EmergencySupplies supplies = emergencySuppliesMapper.selectEmergencySuppliesById(stock.getSuppliesId());
        if (supplies == null) {
            throw new ServiceException("物资信息不存在");
        }

        // 2. 检查是否存在相同物资和存放位置的库存记录
        EmergencySuppliesStock query = new EmergencySuppliesStock();
        query.setSuppliesId(stock.getSuppliesId());
        query.setLocationId(stock.getLocationId());
        EmergencySuppliesStock existingStock = emergencySuppliesStockMapper.selectEmergencySuppliesStockBySuppliesIdAndLocationId(query);

        int rows = 0;
        if (existingStock != null) {
            // 3. 如果存在，更新库存数量
            existingStock.setStockQuantity(existingStock.getStockQuantity() + stock.getQuantity());
            existingStock.setUpdateTime(DateUtils.getNowDate());
            existingStock.setUpdateBy(SecurityUtils.getUsername());
            rows = emergencySuppliesStockMapper.updateEmergencySuppliesStock(existingStock);
        } else {
            // 4. 如果不存在，创建新的库存记录
            stock.setStockQuantity(stock.getQuantity());
            stock.setCreateTime(DateUtils.getNowDate());
            stock.setCreateBy(SecurityUtils.getUsername());
            rows = emergencySuppliesStockMapper.insertEmergencySuppliesStock(stock);
        }

        // 5. 创建入库记录
        EmergencySuppliesRecord record = new EmergencySuppliesRecord();
        record.setSuppliesId(stock.getSuppliesId());
        record.setSuppliesName(stock.getSuppliesName());
        record.setQuantity(stock.getQuantity());
        record.setUnit(supplies.getUnit());  // 设置单位
        record.setLocationId(stock.getLocationId());
        record.setLocationName(stock.getLocationName());
        record.setOperationType("0"); // 0-入库
        record.setOperationTime(DateUtils.getNowDate());
        record.setOperator(SecurityUtils.getUsername());
        record.setOperatorId(SecurityUtils.getUserId());
        record.setBatchNo(stock.getBatchNo());
        record.setProductionDate(stock.getProductionDate());
        record.setExpirationDate(stock.getExpirationDate());
        record.setRemark(stock.getRemark());
        emergencySuppliesRecordService.insertEmergencySuppliesRecord(record);

        return rows;
    }
    
    /**
     * 物资出库
     * 
     * @param stock 应急物资库存信息
     * @return 结果
     */
    @Override
    @Transactional
    public int stockOut(EmergencySuppliesStock stock) {
        // 1. 获取物资信息
        EmergencySupplies supplies = emergencySuppliesMapper.selectEmergencySuppliesById(stock.getSuppliesId());
        if (supplies == null) {
            throw new ServiceException("物资信息不存在");
        }

        // 2. 检查库存是否充足
        EmergencySuppliesStock existingStock = emergencySuppliesStockMapper.selectEmergencySuppliesStockById(stock.getStockId());
        if (existingStock == null) {
            throw new ServiceException("库存记录不存在");
        }
        if (existingStock.getStockQuantity() < stock.getQuantity()) {
            throw new ServiceException("库存不足");
        }

        // 3. 更新库存数量
        existingStock.setStockQuantity(existingStock.getStockQuantity() - stock.getQuantity());
        existingStock.setUpdateTime(DateUtils.getNowDate());
        existingStock.setUpdateBy(SecurityUtils.getUsername());
        int rows = emergencySuppliesStockMapper.updateEmergencySuppliesStock(existingStock);

        // 4. 创建出库记录
        EmergencySuppliesRecord record = new EmergencySuppliesRecord();
        record.setSuppliesId(existingStock.getSuppliesId());
        record.setSuppliesName(existingStock.getSuppliesName());
        record.setQuantity(stock.getQuantity());
        record.setUnit(supplies.getUnit());  // 设置单位
        record.setLocationId(existingStock.getLocationId());
        record.setLocationName(existingStock.getLocationName());
        record.setOperationType("1"); // 1-出库
        record.setOperationTime(DateUtils.getNowDate());
        record.setOperator(SecurityUtils.getUsername());
        record.setOperatorId(SecurityUtils.getUserId());
        record.setReceiver(stock.getReceiver());
        record.setContactInfo(stock.getContactInfo());
        record.setOutstockType(stock.getOutstockType());
        record.setRemark(stock.getRemark());
        emergencySuppliesRecordService.insertEmergencySuppliesRecord(record);

        return rows;
    }
    
    /**
     * 获取即将过期的物资
     * 
     * @return 即将过期物资列表
     */
    @Override
    public List<EmergencySuppliesStock> selectExpiringSupplies() {
        List<EmergencySuppliesStock> list = emergencySuppliesStockMapper.selectExpiringSuppliesList(30);
        // 确保remainDays字段被设置
        if (list != null && !list.isEmpty()) {
            for (EmergencySuppliesStock stock : list) {
                if (stock.getExpirationDate() != null) {
                    // 计算剩余天数
                    Calendar cal = Calendar.getInstance();
                    long now = cal.getTimeInMillis();
                    cal.setTime(stock.getExpirationDate());
                    long expiration = cal.getTimeInMillis();
                    int days = (int) ((expiration - now) / (1000 * 60 * 60 * 24)) + 1;
                    // 设置剩余天数
                    stock.setRemainDays(days);
                }
            }
        }
        return list;
    }
    
    /**
     * 获取物资库存分布情况
     * 
     * @return 分布情况
     */
    @Override
    public List<Map<String, Object>> selectStockDistribution() {
        return emergencySuppliesStockMapper.selectEmergencySuppliesDistribution();
    }
} 